// 非立即防抖
export function debance(fn, awat) {
  let timeout;
  return function () {
    let context = this;
    let args = arguments;
    if (timeout) {
      clearTimeout(timeout);
    }
    timeout = setTimeout(() => {
      fn.apply(context, args);
    }, await);
  };
} // 立即防抖
export const debounce = (func, wait) => {
  let timeout;
  return function () {
    let context = this;
    let args = arguments;
    console.log("timeout1", timeout);

    if (timeout) clearTimeout(timeout);
    console.log("timeout2", timeout);

    let callNow = !timeout;
    timeout = setTimeout(() => {
      timeout = null;
    }, wait);
    if (callNow) {
      console.log("11");
      func.apply(context, args);
    }
  };
};
//  结合版  * @desc 函数防抖 * @param func 函数 * @param wait 延迟执行毫秒数 @param immediate true 表立即执行，false 表非立即执行
export default (fn, awat, immediate) => {
  let timeout;
  return () => {
    let context = this;
    let args = arguments;
    if (timeout) {
      clearTimeout(timeout);
    }
    if (immediate) {
      let callNow = !timeout;
      timeout = setTimeout(() => {
        timeout = null;
      }, awat);
      if (callNow) {
        fn.apply(context, args);
      }
    } else {
      timeout = setTimeout(() => {
        fn.apply(context, args);
      }, awat);
    }
  };
}; // 节流时间戳版本
export const throttle = (fn, wait) => {
  let previous = 0;
  return () => {
    let now = Date.now();
    let context = this;
    let args = arguments;
    if (now - previous > wait) {
      previous = now;
      return fn.apply(context, args);
    }
  };
}; // 定时器版:
export const throttle1 = (fn, wait) => {
  let timeout;
  return () => {
    let context = this;
    let args = arguments;
    if (!timeout) {
      timeout = setTimeout(() => {
        timeout = null;
        fn.apply(context, args);
      }, wait);
    }
  };
}; // 双剑合璧版:
export const throttle2 = (fn, awit, type) => {
  if (type === 1) {
    let previous = 0;
  } else if (type === 2) {
    let timeout;
  }
  return () => {
    let context = this;
    let args = arguments;
    if (type === 1) {
      let now = Date.now();
      if (now - previous > wait) {
        fn.apply(context, args);
        previous = now;
      }
    } else if (type === 2) {
      if (!timeout) {
        timeout = setTimeout(() => {
          timeout = null;
          fn.apply(context, args);
        }, wait);
      }
    }
  };
};
